"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : DMS分布式锁
Case Name   : 触发器获取锁、解锁、锁冲突操作
Create At   : 2023/4/21
Owner       : opentestcase033
Description :
    1.创建源表及触发表
    2.创建触发器函数
    3.创建insert触发器
    4.开启事务A，修改触发器名称，不提交，事务b执行后回退
    5.开启事务B，执行insert触发事件，事务C执行后提交
    6.开启事务C，执行删除触发器的操作
    7.清理环境
Expect:
    1.成功
    2.成功
    3.成功
    4.执行成功
    5.阻塞，事务A回退后执行成功
    6.阻塞，事务B提交后执行成功
    7.成功
History     :
"""

import os
import time
import unittest

from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.ComThread import ComThread


class DmsOck(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.table1 = 't_dms_ock_0019_01'
        self.table2 = 't_dms_ock_0019_02'
        self.function = 'f_dms_ock_0019'
        self.trigger = 'tri_dms_ock_0019'

    def test_dms_ock(self):
        text1 = '-----step1:创建源表及触发表;expect:成功-----'
        self.log.info(text1)
        create_tb = f"drop table if exists {self.table1}, " \
                    f"{self.table2} cascade;" \
                    f"create table {self.table1}(" \
                    f"id1 int, id2 int, id3 int)with (segment=on);" \
                    f"create table {self.table2}(" \
                    f"id1 int, id2 int, id3 int)with (segment=on);"
        create_res = self.pri_sh.execut_db_sql(create_tb)
        self.log.info(create_res)
        self.assertEqual(create_res.count(self.constant.CREATE_TABLE_SUCCESS),
                         2, f"执行失败:{text1}")

        text2 = '-----step2:创建触发器函数;expect:成功-----'
        self.log.info(text2)
        create_fun = f"""drop function if exists {self.function};
        create or replace function {self.function}() returns trigger as
        \$\$
        declare
        begin
          insert into {self.table2} values(new.id1, new.id2, new.id3);
          return new;
        end
        \$\$ language plpgsql;"""
        create_fun_res = self.pri_sh.execut_db_sql(create_fun)
        self.log.info(create_fun_res)
        self.assertIn(self.constant.CREATE_FUNCTION_SUCCESS_MSG,
                      create_fun_res, f"执行失败:{text1}")

        text3 = '-----step3:创建insert触发器;expect:成功-----'
        self.log.info(text3)
        create_tri = f"create trigger {self.trigger} " \
                     f"before insert on {self.table1} " \
                     f"for each row execute procedure {self.function}();"
        create_tri_res = self.pri_sh.execut_db_sql(create_tri)
        self.log.info(create_tri_res)
        self.assertIn(self.constant.TRIGGER_CREATE_SUCCESS_MSG,
                      create_tri_res, f"执行失败:{text2}")

        text4 = '-----step4:开启事务A，重命名触发器，不提交，' \
                '事务B执行后回滚事务A;expect:执行成功-----'
        self.log.info(text4)
        sql1 = f"start transaction;" \
               f"alter trigger {self.trigger} on {self.table1} " \
               f"rename to new_{self.trigger};" \
               f"select pg_sleep(3);" \
               f"rollback;"
        session1 = ComThread(self.pri_sh.execut_db_sql, args=(sql1,))
        session1.setDaemon(True)
        session1.start()
        time.sleep(1)

        text5 = '-----step5:开启事务B，执行insert触发事件，检查触发结果;' \
                'expect:等锁释放，事务A回滚(解锁)，事务B执行成功-----'
        self.log.info(text5)
        sql2 = f'''begin;
        insert into {self.table1} values(100, 200, 300);
        select * from {self.table1};
        select * from {self.table2};
        select pg_sleep(3);
        commit;'''
        session2 = ComThread(self.pri_sh.execut_db_sql, args=(sql2,))
        session2.setDaemon(True)
        session2.start()
        time.sleep(2)

        text6 = '-----step6:开启事务C，删除触发器;' \
                'expect:等锁释放，事务B提交后删除成功-----'
        self.log.info(text6)
        sql3 = f'''begin;
        drop trigger {self.trigger} on {self.table1};
        commit;'''
        session3 = ComThread(self.pri_sh.execut_db_sql, args=(sql3,))
        session3.setDaemon(True)
        session3.start()
        session1.join(10)
        session2.join(10)
        session3.join(10)
        result1 = session1.get_result()
        self.log.info(f'session1_results: {result1}')
        result2 = session2.get_result()
        self.log.info(f'session2_results: {result2}')
        result3 = session3.get_result()
        self.log.info(f'session3_results: {result3}')
        self.assertIn(self.constant.START_TRANSACTION_SUCCESS_MSG,
                      result1, f"执行失败:{text4}")
        self.assertIn('ALTER TRIGGER', result1, f"执行失败:{text4}")
        self.assertIn(self.constant.ROLLBACK_MSG, result1, f"执行失败:{text4}")
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, result2,
                      f"执行失败:{text5}")
        self.assertEqual(result2.count('100 | 200 | 300'), 2, f"执行失败:{text5}")
        self.assertIn(self.constant.COMMIT_SUCCESS_MSG, result2,
                      f"执行失败:{text5}")
        self.assertTrue(self.constant.TRIGGER_DROP_SUCCESS_MSG in result3 and
                        self.constant.COMMIT_SUCCESS_MSG in result3,
                        f"执行失败:{text6}")

    def tearDown(self):
        text7 = '-----step7:清理环境 expect:成功-----'
        self.log.info(text7)
        drop_res = self.pri_sh.execut_db_sql(
            f"drop trigger if exists {self.trigger} on {self.table1};"
            f"drop function if exists {self.function};"
            f"drop table if exists {self.table1}, {self.table2} cascade;")
        self.log.info(drop_res)
        self.assertIn(self.constant.DROP_FUNCTION_SUCCESS_MSG,
                      drop_res, f"删表失败:{text7}")
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
